<template>
  <div class="app-container">
    <list-admin
      ref="admin"
      :key="componentRefresh"
      v-model="listData"
      :entity-conf="entity"
      :list-display="fields"
      :disabled-actions="disabled"
      :query="query"
      :config="config"
      :actions="actions"
      :data-processor="dataProcessor"
    >
      <template v-slot:titleText>
        <span>分账记录</span>
      </template>
      <template v-slot:extraTopButton>
        <span style="margin-right: .5em">
          <el-input v-model="search.staffName" placeholder="员工名/电话" style="width: 150px;" size="medium" clearable>
            <i slot="prefix" class="el-input__icon el-icon-search" />
          </el-input>
        </span>
        <span style="margin-right: .5em">
          <el-input v-model="search.productName" placeholder="产品名称" style="width: 150px;" size="medium" clearable>
            <i slot="prefix" class="el-input__icon el-icon-search" />
          </el-input>
        </span>
        <span style="margin-right: .5em">
          <el-input v-model="search.acc" placeholder="分账账号" style="width: 150px;" size="medium" clearable>
            <i slot="prefix" class="el-input__icon el-icon-search" />
          </el-input>
        </span>
        <span style="margin-right: .5em">
          <el-select v-model="search.store" style="width: 150px;" size="medium" clearable placeholder="门店" @change="changeStore()">
            <el-option v-for="item in stores" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </span>
        <!-- <span style="margin-right: .5em">
          <el-select v-model="search.counter" style="width: 150px;" size="medium" clearable placeholder="台号">
            <el-option v-for="item in counters" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </span> -->
        <span style="margin-right: .5em">
          <el-select v-model="search.team" style="width: 150px;" size="medium" clearable placeholder="业务团队" @change="changeTeam()">
            <el-option v-for="item in teams" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </span>
        <span style="margin-right: .5em">
          <el-select v-model="search.squad" style="width: 150px;" size="medium" clearable placeholder="所属小队">
            <el-option v-for="item in squads" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </span>
        <span style="margin-right: .5em">
          <el-select v-model="search.profitType" style="width: 150px;" size="medium" clearable placeholder="类型">
            <el-option v-for="item in profitTypes" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </span>
        <span style="margin-right: .5em">
          <el-select v-model="search.settled" style="width: 150px;" size="medium" clearable placeholder="分账状态">
            <el-option v-for="item in settledTypes" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </span>
        <span style="margin-right: .5em">
          <el-date-picker
            v-model="search.beforeOrderCreatedTime"
            type="datetime"
            placeholder="订单开始时间"
            style="width: 150px;"
            size="medium"
            value-format="yyyy/MM/dd HH:mm:ss"
          />
        </span>
        <span style="margin-right: .5em">
          <el-date-picker
            v-model="search.afterOrderCreatedTime"
            type="datetime"
            placeholder="订单结束时间"
            style="width: 150px;"
            size="medium"
            value-format="yyyy/MM/dd HH:mm:ss"
          />
        </span>
        <span style="margin-right: .5em">
          <el-date-picker
            v-model="search.beforeCreatedTime"
            type="datetime"
            placeholder="结算开始时间"
            style="width: 150px;"
            size="medium"
            value-format="yyyy/MM/dd HH:mm:ss"
          />
        </span>
        <span style="margin-right: .5em">
          <el-date-picker
            v-model="search.afterCreatedTime"
            type="datetime"
            placeholder="结算结束时间"
            style="width: 150px;"
            size="medium"
            value-format="yyyy/MM/dd HH:mm:ss"
          />
        </span>
        <el-button
          class="filterSpan"
          size="medium"
          icon="el-icon-search"
          style="margin-right: 1em"
          circle
          @click="filterGenerate();fetchData();"
        />
        <el-button slot="reference" size="medium" type="primary" icon="el-icon-download" plain @click="myExport()">
          导出
        </el-button>
      </template>
    </list-admin>
  </div>
</template>

<script>
import ListAdmin from '@/components/EasyAdmin/ListAdmin'
import admin from '@/config'

export default {
  components: { ListAdmin },
  data() {
    return {
      entity: '',
      alias: '',
      config: {},
      fields: [],
      query: {},
      disabled: [],
      entityParam: this.$route.params.entityParam,
      listData: [],
      componentRefresh: 0,
      actions: [],
      filter: {},
      teams: [],
      squads: [],
      stores: [],
      counters: [],
      profitTypes: [
        // { id: '0', name: '酒代分成' },
        // { id: '1', name: '管理员分成' },
        // { id: '2', name: '平台分成' },
        // { id: '3', name: '负责人分成' },
        // { id: '4', name: '场所分成' },
        // { id: '5', name: '资源公司分成' },
        // { id: '6', name: '队长分成' },
        // { id: '7', name: '经纪人分成' },
        // { id: '8', name: '提成' },
        // { id: '9', name: '补贴' },
        // { id: '10', name: '工资' },
        // { id: '11', name: '订台分成' },
        // { id: '12', name: '服务员分成' },
        // { id: '100', name: '剩余余额' },
        // { id: '999', name: '平台手续费' }
      ],
      settledTypes: [
        { id: '0', name: '未分账' },
        { id: '1', name: '已分账' }
      ],
      search: {
        staffName: null,
        productName: null,
        store: null,
        counter: null,
        team: null,
        profitType: null,
        settled: null,
        beforeCreatedTime: null,
        afterCreatedTime: null,
        beforeOrderCreatedTime: null,
        afterOrderCreatedTime: null,
        acc: null,
        squad: null
      }
    }
  },
  created() {
    // Load entities data
    this.alias = 'SettleItem'

    if (!Object.keys(admin.entities).includes(this.alias)) {
      console.log('NO!')
    } else {
      this.config = admin.entities[this.alias]
      this.entity = Object.keys(this.config).includes('entity') ? this.config.entity : this.alias
      this.fields = this.config.list.list_display
      this.disabled = this.config.list.disabled_actions
      this.query = this.config.list.query
      this.actions = this.config.list.actions

      this.getProfitTypes()
      this.getStores()
    }
  },
  methods: {
    getProfitTypes() {
      this.axios.get(`/manage/profit-types`).then((res) => {
        console.log('sss', res.data)
        this.profitTypes = res.data
      })
    },
    myExport() {
      const loading = this.$loading({
        lock: true,
        text: '数据导出中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      // default config
      const exportConf = this.config.list.export
      const confQuery = this.config.list.query
      console.log('exportConf', exportConf)
      console.log('confQuery', confQuery)
      let query = {}; let label = {}; let listQuery = {}
      if (exportConf) {
        if (exportConf.query) { query = exportConf.query }
        if (exportConf.label) { label = exportConf.label }
      }
      if (confQuery) {
        listQuery = confQuery
      }

      // Use current filter
      query = Object.assign({}, listQuery, this.filter, query)
      console.log('query', query)

      this.axios.get('/manage/settle-items', { params: query })
        .then(res => {
          let keys = []
          res.data.forEach(datum => {
            keys = Object.keys(datum)
            keys.forEach(key => {
              if (typeof datum[key] === 'object' && datum[key] !== null) {
                datum[key] = datum[key].__toString ? datum[key].__toString : '[Object]'
              } else if (Array.isArray(datum[key])) {
                datum[key] = '[Array]'
              }
            })
          })

          const data = res.data
          if (label && Object.keys(label).length === 0 && Object.getPrototypeOf(label) === Object.prototype) {
            keys.forEach(v => { label[v] = v })
          }

          const exportExcelCsv = require('@/utils/exportExcelCsv').default
          exportExcelCsv(label, data, `export-settle-item.csv`)
        })
        .finally(() => {
          loading.close()
        })
    },
    changeStore() {
      this.getTeams()
      this.getCounters()
    },
    getStores() {
      this.axios.get(`/manage/stores`, {
        params: {
          limit: 10000000
        }
      }).then(res => {
        this.stores = res.data
      })
    },
    getTeams() {
      this.search.team = null
      this.teams = []
      this.squads = []
      if (this.search.store) {
        this.axios.get(`/manage/teams`, {
          params: {
            '@filter': `entity.getStore().getId() == ${this.search.store}`,
            limit: 100
          }
        }).then(res => {
          this.teams = res.data
        })
      }
    },
    changeTeam() {
      this.search.squad = null
      this.squads = []
      if (this.search.team) {
        this.axios.get(`/manage/squads`, {
          params: {
            '@filter': `entity.getTeam().getId() == ${this.search.team}`,
            limit: 100
          }
        }).then(res => {
          this.squads = res.data
        })
      }
    },
    getCounters() {
      this.search.counter = null
      this.counters = []
      if (this.search.store) {
        this.axios.get(`/manage/counters`, {
          params: {
            '@filter': `entity.getStore().getId() == ${this.search.store}`,
            limit: 10000000
          }
        }).then(res => {
          this.counters = res.data
        })
      }
    },
    fetchData() {
      this.$refs.admin.fetchData()
    },
    filterGenerate() {
      this.filter = {}
      if (this.search.staffName) {
        const expression = `(entity.getSettle().getOrderItem().getOrder().getStaff().getPhone() matches '${this.search.staffName}' 
                          || entity.getSettle().getOrderItem().getOrder().getStaff().getName() matches '${this.search.staffName}')`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
      if (this.search.productName) {
        const expression = `entity.getSettle().getOrderItem().getSpecification().getName() matches '${this.search.productName}'`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
      if (this.search.store) {
        const expression = `entity.getSettle().getOrderItem().getOrder().getStore().getId() == '${this.search.store}'`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
      if (this.search.counter) {
        const expression = `entity.getSettle().getOrderItem().getOrder().getCounter().getId() == '${this.search.counter}'`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
      if (this.search.team) {
        const expression = `entity.getSettle().getOrderItem().getOrder().getTeam().getId() == '${this.search.team}'`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
      if (this.search.squad) {
        const expression = `entity.getSettle().getOrderItem().getOrder().getSquad().getId() == '${this.search.squad}'`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
      if (this.search.profitType) {
        const expression = `entity.getProfitType() == '${this.search.profitType}'`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
      if (this.search.acc) {
        const expression = `entity.getUser().getUsername() == '${this.search.acc}'`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
      if (this.search.settled) {
        const expression = `entity.getSettled() == '${this.search.settled}'`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
      if (this.search.beforeCreatedTime) {
        const expression = `entity.getCreatedTime() >= datetime.get("${this.search.beforeCreatedTime}")`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
      if (this.search.afterCreatedTime) {
        const expression = `entity.getCreatedTime() < datetime.get("${this.search.afterCreatedTime}")`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
      if (this.search.beforeOrderCreatedTime) {
        const expression = `entity.getSettle().getOrderItem().getOrder().getCreatedTime() >= datetime.get("${this.search.beforeOrderCreatedTime}")`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
      if (this.search.afterOrderCreatedTime) {
        const expression = `entity.getSettle().getOrderItem().getOrder().getCreatedTime() < datetime.get("${this.search.afterOrderCreatedTime}")`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
    },
    dataProcessor(context, dataProcessor = {}) {
      // Loading start
      context.list = []
      context.loading = true

      const promise = [
        // Fetch Structure
        context.em.structure().then(res => { context.structure = res }),

        // Fetch Data
        context.em.list(Object.assign(
          /**
               * Combine default constant query to dynamic pager and sort
               * Pager and sort object will change in the page
               */
          {},
          context.query ? context.query : {},
          this.filter,
          context.pager,
          context.sort
        )).then(res => {
          // Assign data
          context.list = res.data
          context.paginator = res.paginator
        })
      ]

      Promise.all(promise.map(p => p.catch(e => e)))
        .then(res => { context.loading = false })
    }
  }
}
</script>

<style lang="scss" scoped>
  .filterSpan {
    margin-right: .5em;
    margin-top: .5em
  }
</style>
